import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter_pickers/more_pickers/route/multiple_link_picker_route.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:flutter_yn_goods/config/app_theme.dart';
import 'package:flutter_yn_goods/generated/assets.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/widgets/widget_picker_style.dart';
import 'package:get/get.dart';

class AddressService {
  static List<Map<String, dynamic>>? _provinces;
  static List<Map<String, dynamic>>? _districts;
  static List<Map<String, dynamic>>? _wards;
  static List<Map<String, dynamic>>? _vietnamAddress;

  static Future<List<Map<String, dynamic>>> loadVietnamAddress() async {
    if (_vietnamAddress != null) {
      return _vietnamAddress!;
    }

    List<Map<String, dynamic>> provinces = (await loadProvinces());
    List<Map<String, dynamic>> districts = (await loadDistricts());
    List<Map<String, dynamic>> wards = (await loadWards());

    for (Map<String, dynamic> province in provinces) {
      province['children'] = districts
          .where((district) => district['ProvinceCode'] == province['Code'])
          .toList();
      province['children']?.forEach((element) {
        element['children'] = wards.where((ward) {
          return ward['DistrictCode'] == element['Code'];
        }).toList();
      });
    }
    _vietnamAddress = provinces;
    return provinces;
  }

  static Future<List<Map<String, dynamic>>> loadProvinces() async {
    if (_provinces != null) {
      return _provinces!;
    }

    final data = await rootBundle.loadString(Assets.provinces);
    // return _parseProvinces(json.decode(data));
    _provinces = json.decode(data).cast<Map<String, dynamic>>();
    return json.decode(data).cast<Map<String, dynamic>>();
  }

  static Future<List<Map<String, dynamic>>> loadDistricts() async {
    if (_districts != null) {
      return _districts!;
    }

    final data = await rootBundle.loadString(Assets.districts);
    _districts = (json.decode(data)).cast<Map<String, dynamic>>();
    return (json.decode(data)).cast<Map<String, dynamic>>();
  }

  static Future<List<Map<String, dynamic>>> loadWards() async {
    if (_wards != null) {
      return _wards!;
    }

    final data = await rootBundle.loadString(Assets.wards);
    _wards = (json.decode(data)).cast<Map<String, dynamic>>();
    return (json.decode(data)).cast<Map<String, dynamic>>();
  }

  static showVietnamAddressPicker(
    Function(List res, List<String> position) onSelect,
  ) async {
    List<Map<String, dynamic>> citys =
        await AddressService.loadVietnamAddress();
    Map<String, dynamic> datas = {};
    citys.forEach((element) {
      Map<String, dynamic> infos = {};
      element['children'].forEach((item) {
        // Map<String, dynamic> items = {};
        infos[item['FullName']] = item['children'].map((item1) {
          // items[item1['FullName']] =
          return item1['FullName'];
        }).toList();
      });
      datas[element['FullName']] = infos;
    });

    Pickers.showMultiLinkPicker(
      Get.context!,
      data: datas,
      columeNum: 3,
      suffix: ['', '', ''],
      pickerStyle: WidgetPickerStyle.createPickerStyle(),
      onConfirm: (List res, List<int> position) async {
        List<Map<String, dynamic>> provinces = (await loadProvinces());
        List<Map<String, dynamic>> districts = (await loadDistricts());
        List<Map<String, dynamic>> wards = (await loadWards());
        clog("你选择了:$res   $position   ${provinces[0]}");
        onSelect.call(res, [
          provinces[position[0]]['Code'],
          districts[position[1]]['Code'],
          wards[position[2]]['Code']
        ]);
      },
    );
  }
}

///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///
class Address {
  String? districtCode;
  String? districtId;
  String? id;
  String? code;
  String? name;
  String? englishName;
  String? fullName;
  String? englishFullName;
  int? administrativeUnitId;
  String? provinceCode;
  String? provinceId;
  List<Address>? children;

  Address({
    this.districtCode,
    this.districtId,
    this.id,
    this.code,
    this.name,
    this.englishName,
    this.fullName,
    this.englishFullName,
    this.administrativeUnitId,
    this.provinceCode,
    this.provinceId,
    this.children,
  });

  Address.fromJson(Map<String, dynamic> json) {
    districtCode = json['DistrictCode']?.toString();
    districtId = json['DistrictId']?.toString();
    id = json['Id']?.toString();
    code = json['Code']?.toString();
    name = json['Name']?.toString();
    englishName = json['EnglishName']?.toString();
    fullName = json['FullName']?.toString();
    englishFullName = json['EnglishFullName']?.toString();
    administrativeUnitId = json['AdministrativeUnitId']?.toInt();
    provinceCode = json['ProvinceCode']?.toString();
    provinceId = json['ProvinceId']?.toString();
    children = [];
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['DistrictCode'] = districtCode;
    data['DistrictId'] = districtId;
    data['Id'] = id;
    data['Code'] = code;
    data['Name'] = name;
    data['EnglishName'] = englishName;
    data['FullName'] = fullName;
    data['EnglishFullName'] = englishFullName;
    data['AdministrativeUnitId'] = administrativeUnitId;
    data['ProvinceCode'] = provinceCode;
    data['ProvinceId'] = provinceId;
    // data['children'] = children;
    return data;
  }
}
